import _ from 'lodash'
import {removeToken, $jui, $utils} from "@jzl/utils";
// import {useRouter} from 'vue-router';

let _isReapTip = false;

const goLoginDefault = () => {
  // default  route
  /*const router = useRouter()

  // 通过路径判断（需要遍历匹配）
  if(router?.getRoutes().some(route => route.path === '/login')) {
    return router.push({
      path: '/login'
    })
  }

  // 通过路由名称判断
  if(router?.hasRoute('login')) {
    return router.push({
      name: 'login'
    })
  }*/

  window.location = '/login';
}

const goLoginPage = () => {

  // if(import.meta.env.MODE === 'development') {
  //   return goLoginDefault();
  // }

  return $utils.dealNoLogin('LOGIN')
}

const handleNoLogin = (error) => {

  if(!_isReapTip) {
    $jui.warning('登录已过期，请重新登录');
    _isReapTip = true;
  }

  let token = _.get(error, 'config.headers.Authorization')
  if(token) removeToken()

  goLoginPage()

  setTimeout(() => {
    _isReapTip = false;
  }, 5000)
}

export const errorHandler = error => {
  let errStatus = _.get(error, 'status') || _.get(error, 'response.status')
  let msg = _.get(error, 'response.data.message') || _.get(error, 'response.data') || _.get(error, "message")
// console.log(error);
  if(!msg || (_.isString(msg) && msg.indexOf('class com.') >= 0)) {
    if (errStatus === 401) {
      msg = '未登录，请先登录。'
    } else if(errStatus === 403) {
      msg = '非法访问';
    } else if(errStatus === 500) {
      msg = '系统错误';
    } else {
      msg = '其他错误';
    }
  }

  if(errStatus === 401) {
    return handleNoLogin(error)
  }

  $jui.warning(msg);

  return Promise.reject(error);
}

export const successHandler = response => {
  // let data = _.get(response, "data");
  // let code = _.get(response, "data.code")
  let ignoreFlag = _.get(response, 'config.headers.j-ignore')
  let silentFlag = _.get(response, 'config.headers.j-silent')
  let isIgnore = ignoreFlag === true || ignoreFlag === 'true';
  let isSilent = silentFlag === true || silentFlag === 'true';

  return response;
  /*if(code === 200 || code === '200' || isIgnore) {
    return response;
  } else if(code === 401 || code === '401') {
    return handleNoLogin(response)
  } else {
    let msg = _.get(response, "data.message")
    let err = new Error(msg);

    err.response = response;
    err.status = code;

    if(!isSilent) {
      ElMessage.warning(msg);
    }

    throw err;
  }*/
}
